//
//  ChatRoomView.swift
//  Chatup
//
//  Created by iron man on 2023/12/10.
//

import SwiftUI
import FirebaseAnalytics

struct ChatRoomView: View {
    @Environment(\.presentationMode) var presentationMode
    @StateObject var viewModel = ChatRoomViewModel()
    @Binding var rid: Int
    @State var newMessage: String = ""
    @FocusState private var isFocused: Bool
    @Binding var item: MsgItem
    @State private var scrollProxy: ScrollViewProxy?
    @State private var scrollToBottom: Bool = false
    @State var chooseDialogItem: Int = -1
    @State var showVIP = false
    @State private var showToast = false
    @State private var showMsgToast = false
    @State var hasMsg = false
    @State var textEditorHeight: CGFloat = 40
    @State private var isShowingDetailView = false
    @State private var isShowingShareView = false
    @State private var isFinish = true
    @State private var image = ""
    
    var body: some View {
        GeometryReader(content: { geometry in
            ZStack {
                VStack(spacing: 0) {
                    HStack {
                        Button(action: {presentationMode.wrappedValue.dismiss()}, label: {
                            Image("icon_back")
                        })
                        Spacer()
                        Text(String.i18nText("tab_chat"))
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(.white)
                        Spacer()
                        Button(action: {}, label: {
                            Image("icon_close")
                        })
                            .opacity(0)
                    }
                    .padding(.horizontal)
                    .padding(.vertical, 8)
                    VStack(alignment: .leading, spacing: 0) {
//                        HomePageViewHeader(choosed: viewModel.choosed, rolelist: viewModel.roleList,  ontapList: {
//                            viewModel.showDialog.toggle()
//                        })
                        HStack {
                            ZStack(alignment: .bottomTrailing) {
                                Image(viewModel.choosed.icon)
                                    .resizable()
                                    .frame(width: 36, height: 36)
                                //                .overlay(
                                //                    RoundedRectangle(cornerRadius: 18)
                                ////                        .stroke(Color.black, lineWidth: 3)
                                //                )
                                Image("icon_online")
                                    .resizable()
                                    .frame(width: 8, height: 8)
                            }
//                            HomePageHeaderItem2(model: viewModel.choosed)
                            Spacer()
                                .frame(width: 10)
                            VStack(alignment: .leading) {
                                Text(viewModel.choosed.name)
                                    .font(.system(size: 16))
                                    .foregroundColor(.white)
                                Text(viewModel.choosed.desc)
                                    .font(.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }
                            Spacer()
                            Button(action: {
                                viewModel.logClickCharaters()
                                viewModel.showDialog.toggle()
                            }, label: {
                                HStack(spacing: 0) {
                                    HStack(spacing: -2) {
                                        ForEach(viewModel.roleList.indices, id: \.self) { index in
                                            ZStack(alignment: .bottomTrailing) {
                                                Image(viewModel.roleList[index].icon)
                                                    .resizable()
                                                    .frame(width: 24, height: 24)
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(Color.black, lineWidth: 3)
                                                    )
                                                Image("icon_online")
                                                    .resizable()
                                                    .frame(width: 8, height: 8)
                                            }
                                        }
                                    }
                                    Image("icon_botom")
                                        .resizable()
                                        .frame(width: 20, height: 20)
                                }
                            })
                        }
                        Spacer()
                            .frame(height: 12)
                    }
                    .padding([.top, .bottom], 0)
                    .padding([.trailing, .leading], 16)
                    Divider()
                    ScrollViewReader { scrollViewProxy in
                        ScrollView {
                            Spacer()
                                .frame(height: 16)
                            ForEach(viewModel.messages, id:\.id) { message in
                                ChatBubbleView(isVip: viewModel.isVip, model: message
                                               , showToast: $showToast)
                                .id(message.id)
                                    .padding(.vertical, 5)
                                    .padding(.horizontal, 16)
                                    .sheet(isPresented: $isShowingDetailView) {
                                        ImageDetailView(image: $image)
                                    }
                            }
                        }
                        .onAppear {
                            if rid > 0 {
                                viewModel.changeId(roleId: rid)
                            }
                            viewModel.initData()
                            scrollViewProxy.scrollTo(viewModel.messages.last?.id)
                        }
                        .onChange(of: viewModel.messages) { _ in
                            withAnimation {
                                scrollViewProxy.scrollTo(viewModel.messages.last?.id, anchor: .bottom)
                            }
                        }
                        .onChange(of: viewModel.outputMsg, perform: { _ in
                            withAnimation {
                                scrollViewProxy.scrollTo(viewModel.messages.last?.id, anchor: .bottom)
                            }
                        })
                        .onTapGesture {
                            isFocused = false
                        }
                    }
                    
                    Divider()
                    
                    Spacer()
                        .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                        .frame(height: 8)
                    
                    HStack(alignment: .center) {
                        if !viewModel.isVip {
                            Button(action: {
                                viewModel.logFrom = "characters_chat_credits"
                                showVIP.toggle()
                                viewModel.logCreditsClick(role_id: String(self.rid))
                            }, label: {
                                VStack(spacing: 0) {
                                    Image("icon_diamond")
                                        .resizable()
                                        .frame(width: 25, height: 25)
                                    Text("\(viewModel.leftCount)/5")
                                        .font(.system(size: 12))
                                        .foregroundColor(.white.opacity(0.6))
                                }
                            })
                        }

                        TextField(String.i18nText("chat_ask"), text: $newMessage)
                            .disabled(!viewModel.isVip && viewModel.currentRole?.roleType != RoleModelType.bot.rawValue)
                            .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                            .font(.system(size: 14))
                            .textFieldStyle(CustomTextFieldStyle(hasMsg: $hasMsg))
                            .cornerRadius(12)
                            .focused($isFocused)
                            .padding(.vertical, 0)
                            .onTapGesture {
                                if !viewModel.isVip, viewModel.currentRole?.roleType != RoleModelType.bot.rawValue {
                                    showVIP.toggle()
                                }
                            }

                        Button(action: {
                            if !viewModel.messages.last!.isFinish && viewModel.messages.last!.messageType == .text && !viewModel.messages.last!.isUser {
                                return
                            }
                            if newMessage.allSatisfy({ $0.isWhitespace }) {
                                return
                            }
                            if !viewModel.isVip {
                                if viewModel.leftCount == 0 {
                                    viewModel.logFrom = "characters_chat_send"
                                    viewModel.showGpt3VipTips = true
                                    UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                                    UserDefaults.standard.synchronize()
                                    showVIP.toggle()
                                    return
                                }
                            }
                            viewModel.refreshUI(msg: newMessage)
                            newMessage = ""
                        }, label: {
                            Image(isFocused || hasMsg ? "icon_chat_bottom_send_green" : "icon_chat_bottom_send_gray")
                                .resizable()
                                .frame(width: 24, height: 24)
                        })
                    }
                    .padding([.top, .bottom], 0)
                    .padding([.trailing, .leading], 16)
                    Spacer()
                        .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                        .frame(height: 8)
                    Divider()
                }
                
                if viewModel.newUser {
                    VStack(alignment: .trailing, spacing: 20) {
                        Spacer()
                        ForEach(viewModel.quickItems.indices, id: \.self) { index in
                            Button(action: {
                                if !viewModel.isVip, viewModel.currentRole?.roleType != RoleModelType.bot.rawValue {
                                    showVIP.toggle()
                                    return
                                }
                                if !viewModel.isVip {
                                    if viewModel.leftCount == 0 {
                                        viewModel.showGpt3VipTips = true
                                        UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                                        UserDefaults.standard.synchronize()
                                        showVIP.toggle()
                                        return
                                    }
                                }
                                viewModel.refreshUI(msg: viewModel.quickItems[index].name)
                            }, label: {
                                HStack {
                                    Spacer()
                                    VStack {
                                        Text(viewModel.quickItems[index].name)
                                            .font(.system(size: 14))
                                    }
                                    .padding(10)
                                    .background(Color(red: 32/255.0, green: 37/255.0, blue: 35/255.0))
                                    .foregroundColor(.white)
                                    .cornerRadius(8)
                                    Spacer()
                                        .frame(width: 12)
                                }
                            })
                        }
                        HStack {
                            Spacer()

                            Button(action: {
                                viewModel.refreshProData()
                            }, label: {
                                HStack{
                                    Image("icon_refresh")
                                    Spacer().frame(width: 4)
                                    Text(String.i18nText("chat_more"))
                                        .lineLimit(1)
                                      .font(Font.system(size: 12))
                                      .foregroundColor(Color(red: 0.53, green: 0.55, blue: 0.59))
                                }.frame(height: 40)
                                .aspectRatio(contentMode: .fit)
                            })
                            Spacer()
                                .frame(width: 12)
                        }
                        
                        Spacer()
                            .frame(height: 40)
                    }
                }
                
                if viewModel.showDialog {
                    HomeDialogView(showDialog: $viewModel.showDialog, chooseDialogIndex: $chooseDialogItem, curRoleId: viewModel.currentRole?.id ?? 0)
                }
            
                if viewModel.showGpt3VipTips {
                    ZStack {
                        Spacer()
                        VStack (spacing: 0){
                            Spacer().background(.red)
                            HStack {
                                VStack (spacing: 0){
                                    HStack{
                                        Text(String.i18nText("chat_no_credit_gpt3.5"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                            
                                    }.frame(height: 100)
                                        .frame(maxWidth:.infinity)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.15, green: 0.15, blue: 0.2))
                                        .cornerRadius(12, corners: .topLeft)
                                        .cornerRadius(12, corners: .topRight)

                                    HStack{
                                        Text("🌟")
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer().frame(width: 12)
                                        Text(String.i18nText("subs_try_for_free"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer()
                                        Image("ic_right")
                                            .resizable()
                                            .frame(width: 24, height: 24)
                                    }.frame(height: 46)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.21, green: 0.84, blue: 0.54))
                                        .cornerRadius(12, corners: .bottomLeft)
                                        .cornerRadius(12, corners: .bottomRight)

                                }.frame( maxWidth:.infinity)
                                    .padding(.horizontal, 12)
                                    .padding(.bottom, 60)
                                    .onTapGesture {
                                        viewModel.logFreeClick(role_id: String(self.rid))
                                        viewModel.logFrom = "characters_chat_free"
                                        showVIP.toggle()
                                    }

                            }
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
                
                if showToast {
                    ToastView(text: "Success!")
                }
                
                if showMsgToast {
                    ToastView(text: String.i18nText("toast_still_in_progress"))
                }
            }
            
        }).onChange(of: item, perform: { value in
                if !viewModel.messages.last!.isFinish && viewModel.messages.last!.messageType == .text && !viewModel.messages.last!.isUser{
                    self.showMsgToast.toggle()
                    hideToastAfterDelay()
                    return
                }
                viewModel.refreshUI(msg: value.text)
            })
            .onChange(of: chooseDialogItem, perform: { value in
                if value < 0 {
                    return
                }
                viewModel.logSwitchCharaters(role_id: String(value))
                if value == 1 || value == 0 {
                    viewModel.changeId(roleId: value)
                } else {
                    if !viewModel.isVip {
                        if value == 2 {
                            viewModel.logFrom = "characters_chat_chracter1"
                        } else if value == 3 {
                            viewModel.logFrom = "characters_chat_chracter"
                        }
                        viewModel.changeId(roleId: value)
                    } else {
                        viewModel.changeId(roleId: value)
                    }
                }
                chooseDialogItem = -1
            })
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kRefreshMsg"))) { _ in
                debugPrint("value")
            }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kAppendMessage"))) { notification in
                let data = notification.object as? [String: Any]
                let messages = data?["msgs"] as? [MsgModel]
                let roleId = data?["roleId"] as? String
                if Int(roleId ?? "0") ?? 0  == rid{
                    viewModel.addLocalMessage(m: messages!.last!)
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("refreshVip"))) { _ in
                DispatchQueue.main.async {
                    viewModel.refreshVip()
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kUpdateLaseMessage"))) { notification in
                let data = notification.object as? MessageModel
                if data != nil && data?.roleId == String(rid){
                    viewModel.messages.removeLast()
                    viewModel.messages.append(data!)
                    viewModel.outputMsg = viewModel.outputMsg + 1
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kGpt3OverSizeMessage"))) { _ in
                viewModel.messages.removeLast()
                if !viewModel.isVip{
                    viewModel.leftCount = 0
                    UserDefaults.standard.setValue(0, forKey: "leftCount")
                    UserDefaults.standard.synchronize()
                }
                if !viewModel.showGpt3VipTips{
                    viewModel.showGpt3VipTips.toggle()
                    UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                    UserDefaults.standard.synchronize()
                }
            }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kGpt4OverSizeMessage"))) { _ in
                viewModel.messages.removeLast()
                if !viewModel.isVip{
                    viewModel.leftCount = 0
                    UserDefaults.standard.setValue(0, forKey: "leftCount")
                    UserDefaults.standard.synchronize()
                }
                if !viewModel.showGpt4VipTips{
                    viewModel.showGpt4VipTips.toggle()
                    UserDefaults.standard.setValue(true, forKey: "gpt4oversize")
                    UserDefaults.standard.synchronize()
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kCopyMessage"))) { notification in
                let model = notification.object as! MessageModel
                let pasteboard = UIPasteboard.general
                pasteboard.string = model.message
                showToast.toggle()
                Analytics.logEvent("chat_answers_copy", parameters: nil)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    withAnimation {
                        showToast.toggle()
                    }
                }
                
            }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kReaskMessage"))) { notification in
                //            debugPrint("value")
                let model = notification.object as! MessageModel
//                viewModel.logReaskClick()
                viewModel.refreshUI(msg: model.message)
            }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kShareMessage"))) { _ in
                isShowingShareView.toggle()
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kMessageBegin"))) { _ in
                 isFinish = false
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kScrollToBottom"))) { notification in
                let data = notification.object as? MessageModel
                withAnimation {
                    viewModel.outputMsg = viewModel.outputMsg + 1
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kMessageComplete"))) { _ in
                 isFinish = true
            }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kOpenImageMessage"))) { notification in
                let model = notification.object as! MessageModel
                viewModel.refreshVip()
                if viewModel.isVip {
                    self.isShowingDetailView = true
                    self.image = model.message
                } else {
                    showVIP.toggle()
                }
            }
            .fullScreenCover(isPresented: $showVIP, content: {
                VipView(viewModel: .init(from: viewModel.logFrom))
            })
            .onChange(of: isFocused, perform: { _ in
                hasMsg = newMessage != ""
            })
    }

    func hideToastAfterDelay() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            withAnimation {
                showMsgToast.toggle()
            }
        }
    }
}

#Preview {
    ChatRoomView(rid: .constant(0), item: .constant(.init(text: "")))
}
